import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'package:http/http.dart' as http; 

const String filename = 'with_keys.json';

void main() {
  try {
    // Read some data.
    final fileData = _readFileSync();
    final jsonData = jsonDecode(fileData);

    // Use that data.
    print('Number of JSON keys: ${jsonData.length}');
  } catch (e) {
    print('Error: $e');
  }
}

String _readFileSync() {
  final file = File(filename);
  try {
    final contents = file.readAsStringSync();
    return contents.trim();
  } catch (e) {
    print('Error reading file: $e');
    rethrow;
  }
}

/*
const String filename = 'with_keys.json';

void main() async {
  // Read some data.
  final fileData = await _readFileAsync();
  final jsonData = jsonDecode(fileData);

  // Use that data.
  print('Number of JSON keys: ${jsonData.length}');
}

Future<String> _readFileAsync() async {
  final file = File(filename);
  final contents = await file.readAsString();
  return contents.trim();
}

*/
void my_eventloop() {
  // https://dart.cn/language/concurrency/#event-loop

  Timer.periodic(Duration(seconds: 1), (timer) {

    print('Processing event...');

  
    http.get(Uri.parse('https://example.com')).then((response) {
      if (response.statusCode == 200) {
        print('Success!');
      }
    }).catchError((error) {
      print('Error: $error');
    });

  
    if (timer.tick >= 5) {
      timer.cancel();
    }
  });
}

Future<String> _readFileAsync(String filename) {
  final file = File(filename);

  // .readAsString() returns a Future.
  // .then() registers a callback to be executed when `readAsString` resolves.
  return file.readAsString().then((contents) {
    return contents.trim();
  });
}

// https://dart.cn/language/concurrency/#streams
void my_stream() {
  Stream<int> stream = Stream.periodic(const Duration(seconds: 1), (i) => i * i);

  Stream<int> sumStream(Stream<int> stream) async* {
    var sum = 0;
    await for (final value in stream) {
      yield sum += value;
    }
  }
}

// https://dart.cn/language/concurrency/#using-isolates
int slowFib(int n) => n <= 1 ? 1 : slowFib(n - 1) + slowFib(n - 2);

// Compute without blocking current isolate.
void fib40() async {
  try {
    var result = await Isolate.run(() => slowFib(40));
    print('Fib(40) = $result');
  } catch (e) {
    print('Error in isolate: $e');
  }
}